import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:grouped_list/grouped_list.dart';

import '../../../../common/models/index.dart';
import '../../../../common/routers/index.dart';
import '../../../../common/style/icon_font.dart';
import '../../../../common/widgets/o2_stateless_widget.dart';
import 'index.dart';

class ProcessPickerPage extends GetView<ProcessPickerController> {
  const ProcessPickerPage({Key? key}) : super(key: key);

  static Future<dynamic> startPicker(ProcessPickerMode mode) async {
    return await Get.toNamed(O2OARoutes.appProcessPicker,
        arguments: {"mode": mode});
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ProcessPickerController>(
      builder: (_) {
        return O2UI.basePopScope(
            child: Scaffold(
                appBar: AppBar(title: Text("process_picker_title".tr)),
                body: SafeArea(
                  child: Obx(() =>
                      controller.state.mode.value == ProcessPickerMode.process
                          ? Column(
                              mainAxisSize: MainAxisSize.max,
                              children: [
                                searchBar(context),
                                const Divider(thickness: 0),
                                Expanded(
                                    flex: 1,
                                    child: Row(
                                      children: [
                                        Expanded(
                                          flex: 1,
                                          child: appListView(context),
                                        ),
                                        const VerticalDivider(width: 1),
                                        Expanded(
                                          flex: 1,
                                          child: processListView(context),
                                        )
                                      ],
                                    ))
                              ],
                            )
                          : appListView(context)),
                )));
      },
    );
  }

  Widget searchBar(BuildContext context) {
    return Container(
      height: 36,
      color: Theme.of(context).colorScheme.surface,
      child: Row(
        children: [
          const SizedBox(width: 10),
          SizedBox(
            width: 22,
            height: 22,
            child: Icon(O2IconFont.search,
                color: Theme.of(context).colorScheme.primary),
          ),
          const SizedBox(width: 10),
          Expanded(
              flex: 1,
              child: TextField(
                autofocus: false,
                focusNode: controller.searchNode,
                controller: controller.searchController,
                decoration: InputDecoration(
                  isDense: true,
                  border: InputBorder.none,
                  hintText: 'home_index_search_placeholder'.tr,
                  hintStyle: Theme.of(context).textTheme.bodySmall,
                ),
                style: Theme.of(context).textTheme.bodyMedium,
                textInputAction: TextInputAction.search,
                // onSubmitted: controller.onSearch,
              )),
        ],
      ),
    );
  }

  Widget appListView(BuildContext context) {
     final style =
        Theme.of(context).textTheme.bodyMedium?.copyWith(fontSize: 16);
    return Obx(() {
      var appList = controller.state.appList.toList();
      return GroupedListView<ProcessApplicationData, String>(
        elements: appList,
        groupBy: (element) {
          var category = element.applicationCategory ?? '';
          if (category.isEmpty) {
            category = 'process_picker_app_no_categroy'.tr;
          }
          return category;
        },
        groupSeparatorBuilder: ((value) => Padding(
            padding: const EdgeInsets.only(left: 8, top: 10, bottom: 10),
            child: Text(
              value,
              style: TextStyle(color: Theme.of(context).hintColor),
            ))),
        itemBuilder: (context, element) {
          return Obx(() {
            final currentApp = controller.state.currentApp.value;
            return Container(
                color: currentApp?.id == element.id ? Theme.of(context).highlightColor :  Theme.of(context).colorScheme.surface,
                child: Padding(
                    padding: const EdgeInsets.only(left: 20),
                    child: ListTile(
                      onTap: () => controller.clickApp(element),
                      title: Text.rich(highlightText(element.name ?? '',
                        controller.state.searchKey, Colors.red, defaultStyle: style)) ,
                    )));
          });
        },
      );
    });
  }

  Widget processListView(BuildContext context) {
    final style =
        Theme.of(context).textTheme.bodyMedium?.copyWith(fontSize: 16);
    return Obx(() {
      return ListView.separated(
          itemBuilder: (context, index) {
            final process = controller.state.processList[index];
            return Container(
                color: Theme.of(context).colorScheme.surface,
                child: ListTile(
                    onTap: () => controller.clickProcess(process),
                    title: Text.rich(highlightText(process.name ?? '',
                        controller.state.searchKey, Colors.red, defaultStyle: style))));
          },
          separatorBuilder: (context, index) {
            return Divider(
              height: 1,
              color: Theme.of(context).dividerColor,
            );
          },
          itemCount: controller.state.processList.length);
    });
  }

  TextSpan highlightText(String text, String highlight, Color color,
      {TextStyle? defaultStyle}) {
    if (highlight.isEmpty) {
      return TextSpan(text: text, style: defaultStyle);
    }

    // 用于存储 TextSpan 的片段列表
    List<TextSpan> textSpans = [];
    int startIndex = 0;

    // 使用 while 循环遍历所有的匹配项
    while (startIndex < text.length) {
      final int matchStart = text.indexOf(highlight, startIndex);

      // 如果找不到更多匹配项，添加剩余的文本
      if (matchStart == -1) {
        textSpans.add(TextSpan(
          text: text.substring(startIndex),
          style: defaultStyle,
        ));
        break;
      }

      // 添加匹配之前的普通文本
      if (matchStart > startIndex) {
        textSpans.add(TextSpan(
          text: text.substring(startIndex, matchStart),
          style: defaultStyle,
        ));
      }

      // 添加高亮文本
      final int matchEnd = matchStart + highlight.length;
      textSpans.add(TextSpan(
        text: text.substring(matchStart, matchEnd),
        style: TextStyle(color: color),
      ));

      // 更新 startIndex 为匹配后的下一个位置
      startIndex = matchEnd;
    }

    return TextSpan(children: textSpans);
  }
}
